package com.qby.common.utils;

import java.io.*;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;

/**
 * @description: 网络流方法
 * @author: qiu bo yang
 * @create: 2020-06-11 17:32
 */
public class NetUtils {
    /**
     * 下载方法
     *
     * @param urlStr   文件地址
     * @param savePath 保存路径
     */
    public static void download(String urlStr, String savePath) {
        URL url;
        try {
            url = new URL(urlStr);
            HttpURLConnection con = (HttpURLConnection) url.openConnection();
            BufferedInputStream bis = new BufferedInputStream(con.getInputStream());
            byte[] b = new byte[1024];
            FileOutputStream fos = new FileOutputStream(savePath);
            int num;
            while ((num = bis.read(b)) != -1) {
                fos.write(b, 0, num);
            }
            bis.close();
            fos.close();
        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /**
     * 获取网页信息
     *
     * @param urlStr      网页地址
     * @param charSetName 编码格式
     * @return
     */
    public static String getHTML(String urlStr, String charSetName) {
        try {
            URL url = new URL(urlStr);
            HttpURLConnection con = (HttpURLConnection) url.openConnection();
            con.setRequestProperty("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/83.0.4103.97 Safari/537.36");
            InputStream in = con.getInputStream();
            InputStreamReader isr = new InputStreamReader(in, charSetName);
            BufferedReader br = new BufferedReader(isr);
            String s;
            StringBuffer sb = new StringBuffer();
            while ((s = br.readLine()) != null) {
                sb.append(s);
            }
            in.close();
            isr.close();
            return sb.toString();
        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }
}
